package com.devilvan.betrice.recruitment.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.devilvan.betrice.recruitment.mapper.BossLabelMapper;
import com.devilvan.betrice.recruitment.po.BossLabelPo;
import com.devilvan.betrice.recruitment.repository.BossLabelRepository;
import com.devilvan.betrice.recruitment.service.BossLabelService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author Evad.Wu
 * @Description Boss直聘 招聘信息-任职要求标签信息 业务逻辑类
 * @date 2022-08-08
 */
@Service
public class BossLabelServiceImpl extends ServiceImpl<BossLabelMapper, BossLabelPo> implements BossLabelService {
    @Resource(name = "bossLabelRepository")
    private BossLabelRepository bossLabelRepository;

    @Override
    public Set<BossLabelPo> checkSaveLabels(Set<String> labels) {
        Set<BossLabelPo> bossLabelPoSet = new HashSet<>();

        Set<BossLabelPo> labelPoSet = Optional.of(labels).map(m -> {
            Set<BossLabelPo> set = null;
            if (!m.isEmpty()) {
                set = this.findByLabelIn(m);
            }
            return set;
        }).orElseGet(HashSet::new);
        if (labelPoSet.isEmpty()) {
            bossLabelPoSet = labels.stream().map(m -> new BossLabelPo(m.trim())).collect(Collectors.toSet());
        } else {
            Set<String> labelSet = labelPoSet.stream().map(BossLabelPo::getLabel).collect(Collectors.toSet());
            Collection<String> intersection = CollUtil.disjunction(labels, labelSet);
            if (!intersection.isEmpty()) {
                bossLabelPoSet = intersection.stream().map(m -> new BossLabelPo(m.trim())).collect(Collectors.toSet());
                labelPoSet.addAll(bossLabelPoSet);
            }
        }
        bossLabelRepository.saveAllAndFlush(bossLabelPoSet);
        return labelPoSet;
    }

    public Set<BossLabelPo> findByLabelIn(Set<String> labels) {
        LambdaQueryWrapper<BossLabelPo> queryWrapper = new QueryWrapper<BossLabelPo>().lambda();
        queryWrapper.in(BossLabelPo::getLabel, labels);
        queryWrapper.groupBy(BossLabelPo::getLabel);
        return new HashSet<>(this.list(queryWrapper));
    }
}
